package com.proj.hot.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.proj.hot.GlobalParams;
import com.proj.hot.R;
import com.proj.hot.utils.DebugUtil;
import com.proj.hot.utils.TimeService;

import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;

/**
 * 登录页
 */
public class LoginActivity extends BaseActivity {


    WebView wx_login;
    boolean isfinish = false;

    private String sn0 = "";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {

                if (GlobalParams.IS_LOGIN) {
                    Toast.makeText(LoginActivity.this, "登陆成功！", Toast.LENGTH_LONG).show();
                    GlobalParams.IS_LOGIN = true;
                    //DebugUtil.toast(LoginActivity.this, "SN:" + GlobalParams.SN + ",accountid:" + GlobalParams.user_id + ",认证的支付类型:" + GlobalParams.feeMode + ",登录返回的支付类型:" + GlobalParams.user_paytype);
                    DebugUtil.i("paytype", "SN:" + GlobalParams.SN + ",accountid:" + GlobalParams.user_id + ",认证的支付类型:" + GlobalParams.feeMode + ",登录返回的支付类型:" + GlobalParams.user_paytype);

                    if (GlobalParams.user_paytype.equals("3")){

                        startService(new Intent(LoginActivity.this, TimeService.class));
                    }
                    handler.removeMessages(0);
                    handler.removeMessages(1);
                    finish();
                }else{
                    handler.sendEmptyMessage(1);
                }
            }


            if (msg.what == 1) {

                isLogin();

                handler.sendEmptyMessageDelayed(0, 2000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        wx_login = (WebView) findViewById(R.id.wx_login);


        //wx_login.setBackgroundColor(getResources().getColor(R.color.transparent));
        //wx_login.setBackgroundResource(R.drawable.home_bg);

        //WebView加载web资源
       // String loginUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=wx72c0156c824b5999&redirect_uri=http%3A%2F%2Fweixin.coolimax.com%2Faccount%2Fcallback%3Fsn%3D" + GlobalParams.SN + "&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        try {
        sn0 = java.net.URLEncoder.encode(GlobalParams.SN, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.i("wxlogin",".URLDecoder.decode异常！");
            sn0 = GlobalParams.SN;
        }
        String loginUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=wx72c0156c824b5999&redirect_uri=http%3A%2F%2Fweixin.coolimax.com%2Faccount%2Fcallback%3Fsn%3D" + sn0 + "&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";

        Log.i("wxlogin","loginUrl = "+loginUrl);
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        wx_login.setBackgroundColor(Color.parseColor("#262626"));
        wx_login.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                Log.i("wxlogin","url = "+url);
                if (url.contains("http://weixin.coolimax.com/account/callback")
                        && url.contains(GlobalParams.SN) && url.contains("code=")) {

                    wx_login.loadUrl(url);
                    wx_login.setVisibility(View.INVISIBLE);
                    handler.sendEmptyMessageDelayed(1, 2500);


                }
                return true;
            }
        });

        //支持javascript
        wx_login.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        wx_login.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        wx_login.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        wx_login.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        wx_login.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        wx_login.getSettings().setLoadWithOverviewMode(true);
        wx_login.loadUrl(loginUrl);

//        getLoginPic();
//
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isfinish = true;
        handler.removeMessages(0);
        handler.removeMessages(1);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isfinish = true;
    }


    private void isLogin() {


//        GlobalParams.IS_LOGIN=true;
//
//        //测试
//        GlobalParams.user_paytype="2";
//        GlobalParams.user_id="1111";
//        if (GlobalParams.IS_LOGIN)
//        return;


        try {



            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
           // String sn0=java.net.URLEncoder.encode(GlobalParams.SN, "UTF-8");
            body.put("sn", GlobalParams.SN);


            RequestParams params = new RequestParams(GlobalParams.reqHost + "account/islogin");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            Log.i("wxlogin","开始判断是否登录！--------心跳--------");
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    Log.i("wxlogin","islogin = "+s);
                    if(s!=null&&!s.equals("")){
                        DebugUtil.i("xintiao","removeMessages----msg.what=1");
                        handler.removeMessages(1);
                    }else{
                        DebugUtil.i("xintiao","islogin返回值为空："+s);
                        DebugUtil.toast(LoginActivity.this,"服务器没有返回登录信息，请稍后重试！");
                    }
                    try {
                        JSONObject jData = new JSONObject(s);

                        JSONObject resphead = jData.getJSONObject("resphead");
                        if (resphead.getString("resultcode").equals("0000")) {

                            JSONObject respbody = jData.getJSONObject("respbody");
                            JSONObject data = respbody.getJSONObject("data");
                            JSONObject account = data.getJSONObject("account");
                            GlobalParams.user_paytype = data.getString("paytype");
                            GlobalParams.user_id = account.getString("accountid");
//                            GlobalParams.user_address=account.getString("address");
                            GlobalParams.user_logo = account.getString("logo");
//                            GlobalParams.user_phone=account.getString("phone");
                            GlobalParams.user_name = account.getString("name");

                            GlobalParams.IS_LOGIN = true;

                            if(GlobalParams.user_paytype.equals("3")){
                                GlobalParams.user_Residualduration=data.getInt("duration");
                                if (GlobalParams.user_Residualduration<=0){
                                    GlobalParams.user_paytype="2";
                                }
                            }



                            DebugUtil.i("islogin","user_paytype="+GlobalParams.user_paytype);
                            //测试-------------------------
//                            GlobalParams.user_paytype="3";
//                            GlobalParams.user_Residualduration=16*60;
                            //测试-------------------------

                            handler.sendEmptyMessage(0);

                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 将字符串转成unicode
     * @param str 待转字符串
     * @return unicode字符串
     */
    public String convert(String str)
    {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++)
        {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>>8); //取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); //取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);

        }
        return (new String(sb));
    }

}
